//
//  WeatherCollectionViewController.m
//  WeatherGuide
//
//  Created by lanou3g on 15/12/17.
//  Copyright © 2015年 李明. All rights reserved.
//

#import "WeatherCollectionViewController.h"
#import "WeathersCollectionViewCell.h"
#import "LocationManager.h"
#import "NSString+wordChange.h"
#import "LifeIndexView.h"
#import "LifeIndexTableViewCell.h"
#import "GetWeatherHandle.h"
#import "AppDelegate.h"
#import "Weather.h"
#import "Suggestion.h"

#import "WeatherScrollView.h"
#import "AqiViewController.h"
#import "ReachCityCollectionViewController.h"
#import "GetWeatherHandle.h"
#import "DelCollectionViewController.h"

@interface WeatherCollectionViewController ()<UITableViewDataSource,UITableViewDelegate>

@property (nonatomic,strong) AppDelegate *app;
@property (nonatomic,strong) Weather *weather;

@end

@implementation WeatherCollectionViewController


- (void)viewDidAppear:(BOOL)animated
{
    [self.collectionView reloadData];
}

//static NSString * const reuseIdentifier = @"Cell";

- (void)viewDidLoad {
    [super viewDidLoad];
    self.collectionView.backgroundColor = [UIColor cyanColor];

    self.app = [UIApplication sharedApplication].delegate;
    
    NSLog(@"=========================");

    self.collectionView.pagingEnabled = YES;
    [self.collectionView registerNib:[UINib nibWithNibName:@"WeathersCollectionViewCell" bundle:[NSBundle mainBundle]] forCellWithReuseIdentifier:@"WeathersCollectionViewCell"];
    
      [LocationManager updataWeatherForCurrentLocationupdata:^{
          [self.collectionView reloadData];
          
      }];
}

- (void)conllectionViewReloadDataAction:(NSNotification *)sender
{
    [self.collectionView reloadData];
    
    NSArray *array = [[NSUserDefaults standardUserDefaults] arrayForKey:@"city"];
    if (![array containsObject:sender.object]) {
        UIAlertController *alertVC =[UIAlertController alertControllerWithTitle:@"对不起" message:@"暂无此城市信息" preferredStyle:UIAlertControllerStyleAlert];
        [self presentViewController:alertVC animated:YES completion:^{
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self dismissViewControllerAnimated:YES completion:nil];
            });
        }];
        
        
        return;
    }
    NSInteger integer = [array indexOfObject:sender.object];
    
    NSIndexPath *indexPath = [NSIndexPath indexPathForItem:integer inSection:0];
    
    [self.collectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionNone animated:NO ];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

#pragma mark <UICollectionViewDataSource>

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
#warning Incomplete implementation, return the number of sections
    return 1;
}


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
#warning Incomplete implementation, return the number of items
    NSArray *array = [[NSUserDefaults standardUserDefaults] arrayForKey:@"city"];
    
    if (array.count == 0) {
        return 1;
    }
//    NSLog(@"%@",array);
    return array.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    WeathersCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"WeathersCollectionViewCell" forIndexPath:indexPath];
    [cell.addButton addTarget:self action:@selector(addButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    cell.lifeIndexTableView.tableView.dataSource = self;
    cell.lifeIndexTableView.tableView.delegate = self;
    [cell.lifeIndexTableView.tableView reloadData];
    [cell.lifeIndexTableView.tableView registerNib:[UINib nibWithNibName:@"LifeIndexTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"LifeIndexTableViewCell"];
//    NSLog(@"111");
    
    NSFetchRequest *requset = [[NSFetchRequest alloc] initWithEntityName:@"Weather"];
    NSArray *array = [[NSUserDefaults standardUserDefaults] arrayForKey:@"city"];
    NSString *str = array[indexPath.row];
    
    if (str != nil) {
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"city CONTAINS %@",str];
        requset.predicate = predicate;
        NSArray *arrayWeather = [self.app.managedObjectContext executeFetchRequest:requset error:nil];
        Weather *weather = arrayWeather.firstObject;
        cell.weather = weather;
        
        self.weather = weather;
    }
    [cell.cityButton addTarget:self action:@selector(cityButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [cell.qltyButton addTarget:self action:@selector(qltyButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    return cell;
}

- (void)cityButtonAction:(UIButton *)sender
{
    [self presentViewController];
}

- (void)presentViewController
{
    NSLog(@"================");
    DelCollectionViewController *delVC = [[DelCollectionViewController alloc] initWithNibName:@"DelCollectionViewController" bundle:[NSBundle mainBundle]];
    
    UINavigationController *delNC = [[UINavigationController alloc] initWithRootViewController:delVC];
    [self presentViewController:delNC animated:YES completion:^{
         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(conllectionViewReloadDataAction:) name:@"conllectionViewReloadDataAction" object:nil];
    }];

}
- (void)qltyButtonAction:(UIButton *)sender{

    AqiViewController *aqiVC = [[AqiViewController alloc] initWithNibName:@"AqiViewController" bundle:[NSBundle mainBundle]];
//    aqiVC.weather = self.weather;
    [self presentViewController:aqiVC animated:YES completion:^{
        aqiVC.weather = self.weather;
    }];
}

- (void)addButtonAction:(UIButton *)sender
{
    NSArray * array = [[NSUserDefaults standardUserDefaults] arrayForKey:@"city"];
    if (array.count == 9) {
      
        [self presentViewController];
        
    }else{
        ReachCityCollectionViewController *reachVC = [[ReachCityCollectionViewController alloc] initWithNibName:@"ReachCityCollectionViewController" bundle:[NSBundle mainBundle]];
        UINavigationController *reachNC = [[UINavigationController alloc] initWithRootViewController:reachVC];
        reachVC.array = [[GetWeatherHandle sharedHandle].dicCityInfo allKeys];
        

        [self presentViewController:reachNC animated:YES completion:^{
            [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(conllectionViewReloadDataAction:) name:@"conllectionViewReloadDataAction" object:nil];
            reachVC.array = [[GetWeatherHandle sharedHandle].dicCityInfo allKeys];

        }];

    }
}


#pragma mark tableView协议
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 7;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPathP
{
  
   
    LifeIndexTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"LifeIndexTableViewCell" forIndexPath:indexPathP];
  
    cell.suggestionLabel.text = [GetWeatherHandle sharedHandle].arrayLifeIndex[indexPathP.row];
    cell.suggestionImageView.image = [GetWeatherHandle sharedHandle].arrayLifeIndexImage[indexPathP.row];
    tableView.backgroundColor = [UIColor clearColor];
    cell.backgroundColor = [UIColor clearColor];
    Suggestion *suggestion = [GetWeatherHandle sharedHandle].arrayLifeIndexLevel[indexPathP.row];
    cell.suggerstion = suggestion;
   
 
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    LifeIndexTableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    Suggestion *suggestion = [GetWeatherHandle sharedHandle].arrayLifeIndexLevel[indexPath.row];
//    NSLog(@"%@",suggestion);
     UIAlertController *altertVC = [UIAlertController alertControllerWithTitle:cell.suggestionLabel.text message:suggestion.txt preferredStyle:UIAlertControllerStyleAlert];
    
        [self presentViewController:altertVC animated:YES completion:^{
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self dismissViewControllerAnimated:YES completion:nil];
            });
    }];
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 60;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 60;
}



- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc] init];
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 100, 40)];
    label.text = @"生活指数";
    label.textColor = [UIColor whiteColor];
    label.font = [UIFont fontWithName:@"Helvetica-Bold" size:18];
    [view addSubview:label];
    view.backgroundColor = [UIColor clearColor];
    return view;
}

#pragma mark <UICollectionViewDelegate>

#pragma mark 点击item事件


/*
// Uncomment this method to specify if the specified item should be highlighted during tracking
- (BOOL)collectionView:(UICollectionView *)collectionView shouldHighlightItemAtIndexPath:(NSIndexPath *)indexPath {
	return YES;
}
*/

/*
// Uncomment this method to specify if the specified item should be selected
- (BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}
*/

/*
// Uncomment these methods to specify if an action menu should be displayed for the specified item, and react to actions performed on the item
- (BOOL)collectionView:(UICollectionView *)collectionView shouldShowMenuForItemAtIndexPath:(NSIndexPath *)indexPath {
	return NO;
}

- (BOOL)collectionView:(UICollectionView *)collectionView canPerformAction:(SEL)action forItemAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender {
	return NO;
}

- (void)collectionView:(UICollectionView *)collectionView performAction:(SEL)action forItemAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender {
	
}
*/

@end
